package com.scitc.pleasurevideo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scitc.pleasurevideo.adapter.HomeAdapter;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.okgoutil.HttpCompleteOrFail;
import com.scitc.pleasurevideo.okgoutil.OkGoUtil;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;
import com.scitc.pleasurevideo.pojo.HomeVo;
import com.scitc.pleasurevideo.pojo.ParsingWebUrlVo;
import com.scitc.pleasurevideo.util.OnClickUtil;
import com.scitc.pleasurevideo.util.ParsingUtil;

import java.util.ArrayList;
import java.util.List;

import static com.scitc.pleasurevideo.Tabhome.chingeAppbarLayout;
import static com.scitc.pleasurevideo.data.ETMan.getPref;
import static com.scitc.pleasurevideo.data.ETMan.savePref;

/**
 * @author 853
 */
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private Context mcontext;
    private SwipeRefreshLayout mSwipeContainer;
    private ListView mMListView;
    private RelativeLayout mRlViewTop;
    private RelativeLayout mRlQuery;
    private ImageView mIgSearchHome;
    private TextView mTvSearchHome;

    private HomeAdapter homeAdapter;
    private List<HomeVo> items = new ArrayList<>();
    private List<HomeVo> homePojos = new ArrayList<>();
    private int oldOnOffsetChanged = 0;
    public static String topBar = "white";


    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        mcontext = getContext();
        //初始化控件
        initView(view);

        //判断显示哪里的数据（缓存还是网络）
        initJudgeData();

        //滑动的监听事件
        onListListener();

        //所有的点击事件
        onClick();
        return view;
    }

    private void onClick() {
        //头部 点击了搜索框 进行跳转
        mRlViewTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OnClickUtil.setViewClickTimes(mRlViewTop);
                ForwardHelper.toSearchActivity((Activity) mcontext);
            }
        });
    }

    /**
     * 判断是显示缓存数据还是网络数据
     */
    private void initJudgeData() {
        if (toGetPref()) {
            homeAdapter.addAllItem(homePojos);
            mSwipeContainer.setRefreshing(false);
        } else {
            initData();
        }
    }

    /**
     * 当显示网络数据时，先加入解析各大视频网站的数据
     */
    private void initData() {
        homePojos.clear();
        List<ParsingWebUrlVo> parsingWebUrlVoList = new ArrayList<>();
        for (int i = 0; i < ParsingUtil.webImgUrlArray.length; i++) {
            ParsingWebUrlVo parsingWebUrlPojo = new ParsingWebUrlVo();
            parsingWebUrlPojo.setWebUrl(ParsingUtil.webUrlArray[i]);
            parsingWebUrlPojo.setIconUrl(ParsingUtil.webImgUrlArray[i]);
            parsingWebUrlPojo.setTitle(ParsingUtil.webNameArray[i]);
            parsingWebUrlVoList.add(parsingWebUrlPojo);
        }
        homePojos.add(new HomeVo(1, null, parsingWebUrlVoList));

        Okgo();

        getVideoIconData();

    }

    /**
     * 获取视频图标
     */
    private void getVideoIconData() {
        OkGoUtil.init().getVideoIconList(new HttpCompleteOrFail() {
            @Override
            public void onComplete(String json) {
                List<ParsingWebUrlVo> parsingWebUrlVoList=new Gson().fromJson(json,new TypeToken<List<ParsingWebUrlVo>>(){}.getType());
                if(parsingWebUrlVoList!=null&&parsingWebUrlVoList.size()>0){
                    for (int i = 0; i < homePojos.size(); i++) {
                        if(homePojos.get(i).getType()==1){
                            homePojos.get(i).getParsingWebUrlPojos().clear();
                            homePojos.get(i).getParsingWebUrlPojos().addAll(parsingWebUrlVoList);
                            homeAdapter.notifyDataSetChanged();
                            toSavePref();
                            break;
                        }
                    }
                }
            }

            @Override
            public void onFile(String information) {

            }
        });
    }

    /**
     * 访问豆瓣解析数据
     */
    private void Okgo() {
        String url = "https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&limit=28";
        OkGo.<String>get(url)
                .tag(mcontext)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        List<DoubanTvVo> doubanTvPojos = user_fromJSON(response.body());
                        if (doubanTvPojos == null || doubanTvPojos.size() < 1) {
                            return;
                        }
                        List<DoubanTvVo> temps = new ArrayList<>();
                        for (int i = 0; i < 4; i++) {
                            temps.add(doubanTvPojos.get(i));
                        }
                        homePojos.add(0, new HomeVo(0, temps, null));
                        List<DoubanTvVo> temps1 = new ArrayList<>();
                        for (int i = 4; i < 10; i++) {
                            temps1.add(doubanTvPojos.get(i));
                        }
                        homePojos.add(new HomeVo(2, temps1, null));
                        List<DoubanTvVo> temps2 = new ArrayList<>();
                        for (int i = 10; i < 16; i++) {
                            temps2.add(doubanTvPojos.get(i));
                        }
                        homePojos.add(new HomeVo(3, temps2, null));
                        List<DoubanTvVo> temps3 = new ArrayList<>();
                        for (int i = 16; i < 22; i++) {
                            temps3.add(doubanTvPojos.get(i));
                        }
                        homePojos.add(new HomeVo(2, temps3, null));
                        List<DoubanTvVo> temps4 = new ArrayList<>();
                        for (int i = 22; i < 28; i++) {
                            temps4.add(doubanTvPojos.get(i));
                        }
                        homePojos.add(new HomeVo(3, temps4, null));

                        refreshLoadData();
                    }
                });

    }

    /**
     * 重新刷新数据
     */
    private void refreshLoadData() {
        if (homePojos == null || homePojos.size() < 1) {
            return;
        }
        toSavePref();
        homeAdapter.addAllItem(homePojos);
        mSwipeContainer.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        mSwipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        mMListView = (ListView) view.findViewById(R.id.mListView);
        mRlViewTop = (RelativeLayout) view.findViewById(R.id.rlViewTop);
        mRlQuery = (RelativeLayout) view.findViewById(R.id.rl_query);
        mIgSearchHome = (ImageView) view.findViewById(R.id.igSearchHome);
        mTvSearchHome = (TextView) view.findViewById(R.id.tvSearchHome);

        homeAdapter = new HomeAdapter(mcontext, items);
        mMListView.setAdapter(homeAdapter);
        mSwipeContainer.setOnRefreshListener(this);
    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        initData();
    }

    /**
     * 将json转换为list类
     *
     * @param source
     * @return
     */
    private List<DoubanTvVo> user_fromJSON(String source) {
        try {
            Gson gson = new Gson();

            String s = source.replace("{\"data\":[", "[");
            String ss = s.replace("]}", "]");

            List<DoubanTvVo> doubanTvPojos = gson.fromJson(ss, new TypeToken<List<DoubanTvVo>>() {
            }.getType());
            return doubanTvPojos;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * list滑动的事件
     */
    private void onListListener() {

        mMListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                View viewChildAt = mMListView.getChildAt(0);
                if (viewChildAt == null) {
                    return;
                }
                if (getScrollY() < 20) {
                    //展开
                    chingeAppbarLayout.OnChingeAppbarLayout(0);
                    mRlViewTop.setBackgroundColor(Color.parseColor("#00000000"));
                    mRlQuery.setBackgroundResource(R.drawable.search_bg_home);
                    mIgSearchHome.setImageResource(R.mipmap.ic_search_white);
                    mTvSearchHome.setTextColor(Color.parseColor("#FFFFFF"));
                    topBar = "white";
                } else if (getScrollY() >= (viewChildAt.getHeight() / 2) - mRlViewTop.getHeight()) {
                    //折叠
                    chingeAppbarLayout.OnChingeAppbarLayout(1);
                    mRlViewTop.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    mRlQuery.setBackgroundResource(R.drawable.listen_search_bg_home_of);
                    mIgSearchHome.setImageResource(R.mipmap.search_for);
                    mTvSearchHome.setTextColor(Color.parseColor("#8D8C9B"));
                    topBar = "black";
                } else {
                    mRlQuery.setBackgroundResource(R.drawable.search_bg_home);
                    mIgSearchHome.setImageResource(R.mipmap.ic_search_white);
                    mTvSearchHome.setTextColor(Color.parseColor("#FFFFFF"));

                    if (oldOnOffsetChanged < getScrollY()) {
                        if (getScrollY() <= 255) {
                            mRlViewTop.setBackgroundColor(Color.argb(getScrollY(), 255, 255, 255));
                        }
                        oldOnOffsetChanged = getScrollY();
                        chingeAppbarLayout.OnChingeAppbarLayout(1);
                    } else {
                        if ((viewChildAt.getHeight() / 2) - mRlViewTop.getHeight() - getScrollY() <= 255) {
                            mRlViewTop.setBackgroundColor(Color.argb(255 - ((viewChildAt.getHeight() / 2) - mRlViewTop.getHeight() - getScrollY()), 255, 255, 255));
                        }
                        oldOnOffsetChanged = getScrollY();
                        chingeAppbarLayout.OnChingeAppbarLayout(1);
                    }
                    topBar = "black";
                }
            }
        });
    }

    /**
     * 获取listview滑动的距离
     *
     * @return
     */
    public int getScrollY() {
        View c = mMListView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = mMListView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }

    /**
     * 将首页的数据进行缓存
     */
    private void toSavePref() {
        Gson gson = new Gson();
        String json = gson.toJson(homePojos);
        savePref(mcontext, "home_data_homepojo", json);
    }

    /**
     * 获取缓存内的首页数据
     *
     * @return
     */
    private boolean toGetPref() {
        String json = getPref(mcontext, "home_data_homepojo", "[]");
        if (json == null || "[]".equals(json)) {
            return false;
        } else {
            Gson gson = new Gson();
            List<HomeVo> list = gson.fromJson(json, new TypeToken<List<HomeVo>>() {
            }.getType());
            if (list == null || list.size() < 1) {
                return false;
            } else {
                homePojos.addAll(list);
                return true;
            }
        }
    }

}
